package cn.yanhu.kuwanapp.utils

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.webkit.JavascriptInterface
import androidx.activity.viewModels
import cn.woochen.comlib.jsbridge.BridgeWebView
import cn.woochen.comlib.jsbridge.OnBridgeCallback
import cn.woochen.comlib.util.UserPref
import cn.yanhu.kuwanapp.common.activity.CommonWebviewActivity
import cn.yanhu.kuwanapp.common.viewmodels.CommonViewModel
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.helper.UserManageHelper

/**
 *
 * 类描述：
 * @author：woochen
 * create at：2021/7/31 7:08 AM
 */
class MainJavascriptInterface(var context: Context,callbacks:Map<String, OnBridgeCallback>): BridgeWebView.BaseJavascriptInterface(callbacks) {

    private var mToken by UserPref(Constants.USER_TOKEN, "")

    override fun send(data: String?): String {
        return ""
    }

    private fun runOnUiThread(block:()->Unit){
        Handler(Looper.getMainLooper()).post {
            block.invoke()
        }
    }

    /**
     * 分享
     */
    @JavascriptInterface
     fun handleShare(link:String?) {
        runOnUiThread {
            SimpleDialogUtil.share(context,link)
        }
    }

    /**
     * 跳转原生页面
     */
    @JavascriptInterface
     fun handlePush(url:String?) {
        logcom("跳转原生界面：${url}")
        runOnUiThread {
            NavigatorHelper.toPage(context,url)
        }
    }

    /**
     * 获取token
     */
    @JavascriptInterface
    fun getToken() :String = mToken

    /**
     * 打开新页面
     */
    @JavascriptInterface
    fun openNewPage(url:String?){
        runOnUiThread {
            CommonWebviewActivity.start(context,url,true)
        }
    }

    @JavascriptInterface
    fun goBack(){
        runOnUiThread {
          if (context is Activity && !(context as Activity).isFinishing) (context as Activity).finish()
        }
    }

}